if (typeof console == "undefined") {    this.console = { log: function (msg) {  } };}
// 如果浏览器不支持websocket，会使用这个flash自动模拟websocket协议，此过程对开发者透明
WEB_SOCKET_SWF_LOCATION = "/swf/WebSocketMain.swf";
// 开启flash的websocket debug
WEB_SOCKET_DEBUG = true;
var ws, name, client_list={};
http_url='http://app.ccieclub.co';

function init() {
    $.post(http_url+'/api.php/customer_service/customer_chat_log.html',{access_token:access_token},function (data) {
        var data=data.data.data
        console.log(data);
        var len=data.length;
        for(var i=0;i<len;i++){
            if(data[i]['is_user']==1){

                $(".newsList").append('<li>'+
                    '<div class="answerHead"><img src="'+data[i]['user_image']+'"/></div>'+
                    '<div class="answers"><img class="jiao" src="./img/zuo.jpg">'+data[i]['content']+'</div>'+
                    '</li>');

            }else{

                $(".newsList").append('  <li> <div class="nesHead"><img src="./img/tou.jpg"></div> <div class="news"><img class="jiao" src="./img/you.jpg">'+data[i]['content']+'</div> </li>');
            }
        }
    });

    $.post(http_url+'/api.php/customer_service/chat_user.html',{access_token:access_token},function (d) {
        var data=d.data;
        var userlist_window = $(".friend");
        var len=data.length;
        for(var i=0;i<len;i++){
            if(i==0){
                userlist_window.append(' <li class="bg user_'+data[i]['user_id']+'" onclick="user_tab(this);" data-id="'+data[i]['user_id']+'"> <div class="liLeft"><img style="width: 42px;height: 41px;" src="'+data[i]['user_image']+'"></div> <div class="liRight"> <span class="intername">'+data[i]['user_name']+'</span> <span class="infor"></span> </div> </li>');
            }else{
                userlist_window.append(' <li  class="user_'+data[i]['user_id']+'" onclick="user_tab(this);" data-id="'+data[i]['user_id']+'"> <div class="liLeft"><img style="width: 42px;height: 41px;"  src="'+data[i]['user_image']+'"></div> <div class="liRight"> <span class="intername">'+data[i]['user_name']+'</span> <span class="infor"></span> </div> </li>');
            }

        }
    });


}
// 连接服务端
function connect() {
    // 创建websocket
    //ws = new WebSocket("ws://"+document.domain+":7272");
    ws = new WebSocket("ws://47.91.241.248:7272");
    // 当socket连接打开时，输入用户名
    ws.onopen = onopen;
    // 当有消息时根据消息类型显示不同信息
    ws.onmessage = onmessage;
    ws.onclose = function() {
        console.log("连接关闭，定时重连");
        connect();
    };
    ws.onerror = function() {
        console.log("出现错误");
    };
}

// 连接建立时发送登录信息
function onopen()
{
    // 登录
    var login_data = '{"type":"login","user_id":1,"client_name":"'+name.replace(/"/g, '\\"');

    ws.send(login_data);
    console.log("websocket握手成功，发送登录数据:"+login_data);
}
access_token = '5b7f60aca7e7f6f8c680b1b219ad3ec6';
// 服务端发来消息时
function onmessage(e)
{

    var dat=e.data.replace("\\","");
    var data = JSON.parse(dat);
    console.log(data);
    switch(data['type']){
        // 服务端ping客户端
        case 'ping':
            ws.send('{"type":"pong"}');
            break;
        case 'login':
            //绑定uid

            $.post(http_url+'/api.php/customer_service/kefu_blind_user.html',{access_token:access_token,client_id:data['client_id']},function () {});
            break;
        // 用户发送消息
        case 'user_message':
            //{"type":"login","client_id":xxx,"client_name":"xxx","client_list":"[...]","time":"xxx"}
            var uid=$('.bg').attr('data-id');
            if(data['uid']==uid){
                var userlist_window = $(".newsList");
                userlist_window.append('   <li> <div class="answerHead"><img src="'+data['user_image']+'"></div> <div class="answers"><img class="jiao" src="./img/zuo.jpg">'+data['message']+'</div> </li>');
            }
            var user=$('.user_'+data['uid']).attr('data-id');
            console.log('.user_'+data['uid']);
            if(user){

            }else{

                console.log(data['user_image']);
                $(".friend").prepend('<li  class="user_'+data['uid']+'" onclick="user_tab(this);" data-id="'+data['uid']+'"> <div class="liLeft"><img style="width: 42px;height: 41px;"  src="'+data['user_image']+'"></div> <div class="liRight"> <span class="intername">'+data['user_name']+'</span> <span class="infor"></span> </div> </li>');
            }

            break;
        // // 发言
        // case 'say':
        //     //{"type":"say","from_client_id":xxx,"to_client_id":"all/client_id","content":"xxx","time":"xxx"}
        //     say( data['content'], data['time']);
        //     break;
        // // 用户退出 更新用户列表
        // case 'logout':
        //     //{"type":"logout","client_id":xxx,"time":"xxx"}
        //     say(data['from_client_id'], data['from_client_name'], data['from_client_name']+' 退出了', data['time']);
        //     delete client_list[data['from_client_id']];
        //     flush_client_list();
    }
}
function user_tab(lom){
    $(lom).addClass('bg').siblings().removeClass('bg');
    var intername=$(lom).children('.liRight').children('.intername').text();
    $('.internetName').text(intername);
    var id =$(lom).attr('data-id');

    $('.newsList').html('');
    $.post(http_url+'/api.php/customer_service/customer_chat_log.html',{access_token:access_token,'uid':id,list_rows:1000},function (d) {
        var data=d.data.data;
        var userlist_window = $(".newsList");
        var len=data.length;
        for(var i=0;i<len;i++){
            if(data[i]['is_user']==1){
                userlist_window.append('   <li> <div class="answerHead"><img src="'+data[i]['user_image']+'"></div> <div class="answers"><img class="jiao" src="./img/zuo.jpg">'+data[i]['content']+'</div> </li>');
            }else{
                userlist_window.append('   <li> <div class="nesHead"><img src="./index_files/6.jpg"></div> <div class="news"><img class="jiao" src="./img/you.jpg">'+data[i]['content']+' </li>');

            }

        }
    });
}
$(function () {

    $('.face').click(function(event){
        $(this).sinaEmotion();
        event.stopPropagation();
    });
    $('.sendBtn').on('click',function(){
        var news=$('#dope').val();
        if(news==''){
            alert('不能为空');
        }else{
            var uid=$('.bg').attr('data-id');
            $.post(http_url+'/api.php/customer_service/customer_message.html',{access_token:access_token,uid:uid,content:news},function (d) {
                if(d.code==0){

                    $('#dope').val('');
                    var str='';
                    str+='<li>'+
                        '<div class="nesHead"><img src="./index_files/6.jpg"/></div>'+
                        '<div class="news"><img class="jiao" src="./img/you.jpg">'+news+'</div>'+
                        '</li>';
                    $('.newsList').append(str);
                    // setTimeout(answers,1000);
                    // $('.conLeft').find('li.bg').children('.liRight').children('.infor').text(news);
                    $('.RightCont').scrollTop($('.RightCont')[0].scrollHeight );
                }
            })

        }

    })
    function answers(){
        var arr=["你好","今天天气很棒啊","你吃饭了吗？","我最美我最美","我是可爱的僵小鱼","你们忍心这样子对我吗？","spring天下无敌，实习工资850","我不管，我最帅，我是你们的小可爱","段友出征，寸草不生","一入段子深似海，从此节操是路人","馒头：嗷","突然想开个车","段子界混的最惨的两个狗：拉斯，普拉达。。。"];
        var aa=Math.floor((Math.random()*arr.length));
        var answer='';
        answer+='<li>'+
            '<div class="answerHead"><img src="./img/tou.jpg"/></div>'+
            '<div class="answers"><img class="jiao" src="./img/zuo.jpg">'+arr[aa]+'</div>'+
            '</li>';
        $('.newsList').append(answer);
        $('.RightCont').scrollTop($('.RightCont')[0].scrollHeight );
    }
    $('.ExP').on('mouseenter',function(){
        // $('.emjon').show();
        $(this).sinaEmotion();
        event.stopPropagation();
    })
    $('.emjon').on('mouseleave',function(){
        $('.emjon').hide();
    })
    $('.emjon li').on('click',function(){
        var imgSrc=$(this).children('img').attr('src');
        var str="";
        str+='<li>'+
            '<div class="nesHead"><img src="img/6.jpg"/></div>'+
            '<div class="news"><img class="jiao" src="img/you.jpg"><img class="Expr" src="'+imgSrc+'"></div>'+
            '</li>';
        $('.newsList').append(str);
        $('.emjon').hide();
        $('.RightCont').scrollTop($('.RightCont')[0].scrollHeight );
    });

// 搜索框
    function searchToggle(obj, evt){
        var container = $(obj).closest('.search-wrapper');

        if(!container.hasClass('active')){
            container.addClass('active');
            evt.preventDefault();
        }
        else if(container.hasClass('active') && $(obj).closest('.input-holder').length == 0){
            container.removeClass('active');
            // clear input
            container.find('.search-input').val('');
            // clear and hide result container when we press close
            container.find('.result-container').fadeOut(100, function(){$(this).empty();});
        }
    }

    function submitFn(obj, evt){
        value = $(obj).find('.search-input').val().trim();

        _html = "您搜索的关键词： ";
        if(!value.length){
            _html = "关键词不能为空。";
        }
        else{
            _html += "<b>" + value + "</b>";
        }

        $(obj).find('.result-container').html('<span>' + _html + '</span>');
        $(obj).find('.result-container').fadeIn(100);

        evt.preventDefault();
    }

// 菜单选项卡
    !function(window) {
        "use strict";

        var doc = window.document
            , ydui = {};

        $(window).on('load', function() {});

        var util = ydui.util = {

            parseOptions: function(string) {},

            pageScroll: function() {}(),

            localStorage: function() {}(),

            sessionStorage: function() {}(),

            serialize: function(value) {},

            deserialize: function(value) {}
        };

        function storage(ls) {}

        $.fn.emulateTransitionEnd = function(duration) {}
        ;

        if (typeof define === 'function') {
            define(ydui);
        } else {
            window.YDUI = ydui;
        }

    }(window);

    !function(window) {
        "use strict";

        function Tab(element, options) {
            this.$element = $(element);
            this.options = $.extend({}, Tab.DEFAULTS, options || {});
            this.init();
            this.bindEvent();
            this.transitioning = false;
        }

        Tab.TRANSITION_DURATION = 150;

        Tab.DEFAULTS = {
            nav: '.tab-nav-item',
            panel: '.tab-panel-item',
            activeClass: 'tab-active'
        };

        Tab.prototype.init = function() {
            var _this = this
                , $element = _this.$element;

            _this.$nav = $element.find(_this.options.nav);
            _this.$panel = $element.find(_this.options.panel);
        }
        ;

        Tab.prototype.bindEvent = function() {
            var _this = this;
            _this.$nav.each(function(e) {
                $(this).on('click.ydui.tab', function() {
                    _this.open(e);
                });
            });
        }
        ;

        Tab.prototype.open = function(index) {
            var _this = this;

            index = typeof index == 'number' ? index : _this.$nav.filter(index).index();

            var $curNav = _this.$nav.eq(index);

            _this.active($curNav, _this.$nav);

            _this.active(_this.$panel.eq(index), _this.$panel, function() {
                $curNav.trigger({
                    type: 'opened.ydui.tab',
                    index: index
                });
                _this.transitioning = false;
            });
        }
        ;

        Tab.prototype.active = function($element, $container, callback) {
            var _this = this
                , activeClass = _this.options.activeClass;

            var $avtive = $container.filter('.' + activeClass);

            function next() {
                typeof callback == 'function' && callback();
            }

            $element.one('webkitTransitionEnd', next).emulateTransitionEnd(Tab.TRANSITION_DURATION);

            $avtive.removeClass(activeClass);
            $element.addClass(activeClass);
        }
        ;

        function Plugin(option) {
            var args = Array.prototype.slice.call(arguments, 1);

            return this.each(function() {
                var target = this
                    , $this = $(target)
                    , tab = $this.data('ydui.tab');

                if (!tab) {
                    $this.data('ydui.tab', (tab = new Tab(target,option)));
                }

                if (typeof option == 'string') {
                    tab[option] && tab[option].apply(tab, args);
                }
            });
        }

        $(window).on('load.ydui.tab', function() {
            $('[data-ydui-tab]').each(function() {
                var $this = $(this);
                $this.tab(window.YDUI.util.parseOptions($this.data('ydui-tab')));
            });
        });

        $.fn.tab = Plugin;

    }(window);
})
